package service

import (
	"context"
	"gf2DemoServer/internal/dao"
	"gf2DemoServer/internal/model"
	"gf2DemoServer/internal/model/entity"
	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

type sUser struct{}

var insUser *sUser

func User() *sUser {
	if insUser == nil {
		insUser = &sUser{}
	}
	return insUser
}

// Login 登录
func (s *sUser) Login(ctx context.Context, in *model.UserLoginInput) (sUserEntity *entity.User, err error) {
	sUserEntity, err = s.GetInfoByMobile(ctx, in.Mobile)
	if err != nil {
		return
	}
	if sUserEntity == nil {
		return nil, gerror.New(`会员不存在`)
	}
	if sUserEntity.Password != gmd5.MustEncrypt(in.Password) {
		return nil, gerror.New(`密码错误`)
	}
	return
}

// GetInfoByMobile 根据手机号获取用户信息
func (s *sUser) GetInfoByMobile(ctx context.Context, mobile string) (sUser *entity.User, err error) {
	err = dao.User.Ctx(ctx).Where(g.Map{
		dao.User.Columns().Mobile: mobile,
	}).Scan(&sUser)
	return
}
